/**
 * @author kidy
 */
var QS_MarketIndex=function(profile,callback){
    this.container = null;
    this.id = null;
    this.profile={
        chartCfg:{days:1},
        chartProfile:{
            lineType: "montain",
            showX: true,
            showY: true
        },
        chartFixed:false,
        chartHeight:180,

        hasSetting:true,
        settingPanel:null,
        showFirstLabel:false,
        showTimeLabel:false,
        showInterTime:true,
        showInterHour:true,//only show interHour label
        isAPI:true,
        percentage:true,
        isFormat:false,//whether need format
        isUnit:false, //whether need change separate
        fixHeight:true,
        numberSeparate: "",//between number and unit
        gridColumns:[],
        colConfig:{"Chg":{"decimal":2}, "Chg%":{"decimal":2}, "LastPrice":{"decimal":2}},
        tabConfig:{},
        clickToggle:false, 
        headerRow: false,
        showTime: true,

        autoSlideToActiveTab:true,
        menuList:["canada","us","ms","asian","european"],
        openedMenu:null,

        customTickValidataion:null,
        customMenu:null
    };
    this.callback=callback||{};
    this.staticValue={
        winTitle:26,
        padheight:5,
        minWidth:120,
        defaultValue:"--"
    };
    var qslan=QS_Lang.marketindices;
    //default data
    this.regionInfo={
        "canada":{
            txt:qslan["canada"],
            tickers:['0P00001FJG','0P00001G7J', '0P00001G7B', '0P00001GJH', '0P00001GJK','0P00008IVF','0P00008PAC', '0P00001QO6']
        },
        "us":{
            txt: qslan["us"],
            tickers:['0P00001FJG','0P00001G7J', '0P00001G7B', '0P00001GJH', '0P00001GJK']
        },
        "ms":{
            txt: qslan["ms"],
            tickers:['0P00001GJH','0P00001GJI', '0P00001GJJ', '0P00001GJK']
        },
        "asian":{
            txt: qslan["asian"], 
            tickers:['0P00006NNM','0P00006MR4', '0P00001FL8', '0P00001G5J', '0P00001MUH']
        },
        "european":{
            txt: qslan["european"], 
            tickers: ['0P00001IS1','0P00008ICX', '0P00001FKV', '0P00006F1A', '0P00006NOT']
        }
    };
    this.tickersInfo={
        "canada":{  
            '0P00001GJH':QS_Lang.marketindices["mtn_mstar_usmarket"],
            '0P00001GJK':QS_Lang.marketindices["ms"]+" "+QS_Lang.marketindices["mtn_smallcap"],
            '0P00008IVF':QS_Lang.marketindices["mtn_sp/tsx"],
            '0P00008PAC':QS_Lang.marketindices["mtn_sp/tsx60"], 
            '0P00001QO6':QS_Lang.marketindices["mtn_sp/tsx_venture"], 
            '0P00001FJG':QS_Lang.marketindices["mtn_djia"],
            '0P00001G7J':QS_Lang.marketindices["mtn_sp500"],
            '0P00001G7B':QS_Lang.marketindices["mtn_nasdaq"]
        },"us":{    
            '0P00001FJG':QS_Lang.marketindices["mtn_djia"],
            '0P00001G7J':QS_Lang.marketindices["mtn_sp500"],
            '0P00001G7B':QS_Lang.marketindices["mtn_nasdaq"],
            '0P00001GJH':QS_Lang.marketindices["mtn_mstar_usmarket"],
            '0P00001GJK':QS_Lang.marketindices["ms"]+" "+QS_Lang.marketindices["mtn_smallcap"]
        },"ms":{    
            '0P00001GJH':QS_Lang.marketindices["mtn_usmarket"],
            '0P00001GJI':QS_Lang.marketindices["mtn_largecap"], 
            '0P00001GJJ':QS_Lang.marketindices["mtn_midcap"], 
            '0P00001GJK':QS_Lang.marketindices["mtn_smallcap"]
        },"asian":{ 
            '0P00006NNM':QS_Lang.marketindices["mtn_shanghai"],
            '0P00006MR4':QS_Lang.marketindices["mtn_nikkei"],
            '0P00001FL8':QS_Lang.marketindices["mtn_hangseng"],
            '0P00001G5J':QS_Lang.marketindices["mtn_bombay"],
            '0P00001MUH':QS_Lang.marketindices["mtn_australia"]
        },"european":{
            '0P00001IS1':QS_Lang.marketindices["mtn_ftse100"],
            '0P00008ICX':QS_Lang.marketindices["mtn_cac40"],
            '0P00001FKV':QS_Lang.marketindices["mtn_daxfrank"], 
            '0P00006F1A':QS_Lang.marketindices["mtn_aex"], 
            '0P00006NOT':QS_Lang.marketindices["mtn_smi"]
        }
    }
    this.timezone={
        '0P00001FJG':"EST",
        '0P00001G7J':"EST",
        '0P00001G7B':"EST",
        '0P00001GJH':"EST",
        '0P00001GJK':"EST",
        '0P00001GJI':"EST",
        '0P00001GJJ':"EST",
        '0P00001GJK':"EST",
        '0P00006NNM':"CST",
        '0P00006MR4':"JST",
        '0P00001FL8':"CST",
        '0P00001G5J':"IST",
        '0P00001MUH':"EDT",
        '0P00001IS1':"GMT",
        '0P00008ICX':"CET",
        '0P00001FKV':"CET",
        '0P00006F1A':"CET",
        '0P00006NOT':"CET"
    };
    this._textKey = document.body.textContent ? 'textContent' : 'innerText';
    this.lastSubscribeTicker=null;
    this.miniChart=null;
    this.dataGrid = null;
    this.activeRow = null;
    this.loaded=false;
    if(profile.menuList&&profile.menuList.length>0){
        this.profile.menuList=profile.menuList;
    }
    if(profile.gridColumns&&profile.gridColumns.length>0){
        this.profile.gridColumns=profile.gridColumns;
    }
    $.extend(true,this.profile, profile);
};
QS_MarketIndex.prototype = {
    init: function(containerId,conmponentId){
        this.container = $('#' + containerId);
        this.id = conmponentId;
        if(this.profile.customTickValidataion){
            this.tValidation = this.profile.customTickValidataion;
        }else{
            this.tValidation = new tickerValidation(17);
            this.tValidation.needFilterSecurityType = false;
        }
        this._createDom();
        this._initMenu();
        this.scrollPanel = new Util.ScrollPanel(this.el.find(".grid"),{showX:false,delayRun:false,showY:this.profile.fixHeight});
        if(this.profile.hasSetting){
            this._createSettingPanel();
        }
    },
    setTickers:function(regionTickers){
        for(var region in regionTickers){
            if(!this.regionInfo[region]){
                this.regionInfo[region]={txt:region,tickers:regionTickers[region]};
            }else{
                this.regionInfo[region]["tickers"]=regionTickers[region];
            }
        }
    },
    setMenusName:function(menuNames){
        for(var region in menuNames){
            if(!this.regionInfo[region]){
                this.regionInfo[region]={txt:menuNames[region],tickers:[]};
            }else{
                this.regionInfo[region]["txt"]=menuNames[region];
            }
        }
    },
    setTickersName:function(tickerNames){
       $.extend(true,this.tickersInfo,tickerNames);
    },
    setTimeZones:function(timezone){
        $.extend(true,this.timezone,timezone);
    },
    setLoadingHandle:function(showHandle,hiddenHandle){
        if(typeof showHandle=="function"){
            this.showLoading=function(){
                showHandle();
            }
        }
        if(typeof hidden=="function"){
            this.hideLoading=function(){
                hiddenHandle();
            }
        }
    },
    _createDom:function(){
        var html='<div class="qs-marketindex">'+
                    '<div class="tabmenu"></div>'+
                    '<div class="grid"></div>'+
                    '<div class="minichart" style="visibility:hidden;"></div>'+
                '</div>';
        this.el = $(html);
        this.el.appendTo(this.container);
        if(this.profile.width){
            this.el.css({
                width: this.profile.width
            });
        }
        if(!this.profile.isAPI&&!isNaN(this.profile.height)){//if is api, will minus
            this.profile.height-=this.staticValue.winTitle;
        }   
        if(this.profile.width<300){//if the width is too narrow, will add special class
            this.el.find(".tabmenu").addClass("homepage");
        }
    },
    menuOnActive:function(menuId){
        if(this.currentTabMenuId != menuId){
            this.currentTabMenuId = menuId;
            this.activeRow = null;
            if (!this.dataGrid) {
                this._initGrid();
            }else if(!this.profile.chartFixed){
                this.el.find(".minichart").css({"visibility":"hidden"}).appendTo(this.el);
            }
            this._reBuildGridData(menuId);
        }
    },
    _initMenu: function(){
        if(!this.profile.customMenu){
            var self = this;
            var cb = {
                onActive: function(tab){
                    self.menuOnActive(tab.id);
                }
            };
            this.tabMenu = new Util.TabMenu(this.el.find(".tabmenu"), this.getMenuData(), cb, {
                autoResize:true,
                tabsList: false,
                vertical: false,
                activeTabId: this.profile.openedMenu,
                autoSlideToActiveTab:this.profile.autoSlideToActiveTab,
                needTitle:true 
            });
        }else{
            this.tabMenu = customMenu;
        }
    },
    _getCols:function(){
        var lan=QS_Lang.marketindices,cols=[{header: 'id',dataIndex: 'id',dataType: 'string',hide: true}];
        this.columnMap = {
            "UpDown": {header: '<span style="display:none;">Up/Down</span>',dataIndex: 'UpDown',className: 'column-updown',align: 'center', per:5},
            "Symbol":{header: '',dataIndex: 'Symbol',dataType: 'string', per:28, className: 'symbol-name'},//added by wind @ 20120326 
            "Date":{header: lan["mk_coldate"],dataIndex: 'Date',align: 'right',dataType: 'Date',dataFormat: 'yyyy-M-d',className: 'bold-cell',per:18},
            "LastPrice":{header: lan["mk_collast"],dataIndex: 'LastPrice',align: 'right',dataType: 'float',per:18}, 
            "Chg":{header: lan["mk_colchg"],dataIndex: 'Chg',align: 'right',dataType: 'float',className: 'bold-cell',per:16}, 
            "Chg%":{header: lan["mk_colchgp"],dataIndex: 'Chg%',align: 'right',dataType: 'float',className: 'bold-cell',per:15}
        }
        $.extend(true,this.columnMap,this.profile.colConfig);
        if(this.profile.gridColumns.length>0){
            var columns=this.profile.gridColumns,perSum=0;
            for(var i=0,l=columns.length;i<l;i++){
                if(this.columnMap[columns[i]]){
                    perSum += this.columnMap[columns[i]]["per"];
                    cols.push(this.columnMap[columns[i]]);
                }
            }
            for (var i=0,l=cols.length;i<l;i++) {
                if(typeof cols[i]["per"]!='undefined'){
                    cols[i]["width"] = cols[i]["per"] / perSum * 100 + "%";
                }
            }
        }else{
            var tempcol=null;
            for(var dataindex in this.columnMap){
                tempcol= this.columnMap[dataindex];
                tempcol["width"] =tempcol["per"]+ "%";
                cols.push(tempcol);
            }
        }
        return cols;
    },
    _removeLabelTime:function(timeStr){
        //"09:30 AM"->"09:30";
        return $.trim(timeStr).replace(/\s*(PM|AM|a.m.|p.m.)/ig,"");
    },
    _trim:function(timeStr){
        return $.trim(timeStr).replace(/\s/ig,"");
    },
    _isIntNum:function(timeStr){
        return timeStr.indexOf(":00")>0;
    },
    _getPureIntPart:function(timeStr){
        //"09:30 AM"-> 9
        return parseInt(timeStr.replace(/:\d*\s*\w*/ig,"").replace(/^0*/g,""));
    },
    _getIntPart:function(timeStr){
        //"09:30 AM"->"9AM";
        return timeStr.replace(/^0*/g,"").replace(/:(\d*\s*)/ig,"");
    },
    _convertTF:function(timeStr){
        //"9:30 PM"-> 21:30
        var pre=/pm/ig.test(timeStr)?12:0,returnValue=this._getPureIntPart(timeStr);
        var hour = returnValue>=12?returnValue:pre+returnValue;
        returnValue = timeStr.replace(/\d+(?=:)/ig,hour);
        return this._removeLabelTime(returnValue);
    },
    _processData:function(t){
        var isInt=false;
        for(var i=t.length-1;i>=0;i--){
            isInt=false;
            if(t[i][1]==null||typeof t[i][1] == "number"||typeof t[i][1]=='undefined'){
                t.splice(i,1);
                continue;
            }
            if(this._isIntNum(t[i][1])) {//is inter time
                isInt=true;
            }

            if(this.profile.showInterHour&&!isInt){//remove un inter time
                t.splice(i,1);
            }else{
                if(this.profile.showFirstLabel&&i==0){
                    t[i][1]=this._trim(t[i][1]);
                    continue;
                }
                if(!this.profile.showTimeLabel){//don't display AM/a.m.
                    t[i][1]=this._convertTF(t[i][1]);
                }else if(this.profile.showInterTime){//display 9AM/9a.m.
                    t[i][1]=this._getIntPart(t[i][1]);
                }
            }
        }
    },
    onStartDraw:function(data){
        if(this.profile.chartCfg.days==1){
            var t=[];
            if(data[0].price){
                this._processData(data[0].price.xAxis);
            }
        }
    },
    _initGrid: function(){
        var self = this;
        var cb = {
            onRowSelected: function(e, row){
                var gkey = row.id;//self.gKeyList[self.currentTabMenuId]["gKeyList"][0];
                if(!self.activeRow){
                    self.activeRow=row;
                    self._activeRow(row,true,function(){self._animateComplete();});
                }else{
                    if(self.activeRow==row){
                        if(!self.profile.clickToggle) return;
                        self.activeRow=null;
                        self._activeRow(row,false);
                    }else{
                        self._activeRow(self.activeRow,false);
                        self._expanseRow(self.activeRow.el,false);
                        self.activeRow=row;
                        self._activeRow(row,true);
                    }
                }
                if(!self.activeRow){//unactive
                    self.el.find(".minichart").hide();
                    self._expanseRow(row.el,false,function(){self._animateComplete();});
                    row.el.removeClass("rtq-grid-row-selected");
                }else{
                    self._expanseRow(self.activeRow.el,true,function(){self._animateComplete();});
                    self.el.find(".minichart").show();
                    self.el.find(".minichart").css("visibility","hidden");
                    self._drawMiniChart(row, gkey,function(data){
                        //alert("draw mini chart callback");
                        if(self.activeRow){
                            self.el.find(".minichart").css({"visibility":"visible","marginTop":(self.rowHeight/2)});
                        }
                        //self._animateComplete();
                        if(self.profile.showTime){
                            var time = self._getLastTimefromData(data);
                            var timezone = "";
                            if(self.activeRow&&self.activeRow.data&&self.activeRow.data.id){
                                if(gData&&gData[self.activeRow.data.id]&&gData[self.activeRow.data.id]["performanceId"]){
                                    var tid = gData[self.activeRow.data.id]["performanceId"];
                                    if(self.timezone&&self.timezone[tid]){
                                        timezone =self.timezone[tid];
                                    }
                                }
                            }
                            self.el.find('.rtc-legend-txt .time').html(time+" "+timezone);
                        }
                    },function(data){
                        self.onStartDraw(data);
                    });
                    var legend = self.el.find('.rtc-legend-txt .ticker');
                    if (legend.length > 0) {
                        var name = row.cells.Symbol.text;
                        legend.html(name);
                    }
                }
            }
        };
        this.dataGrid = new Util.DataGrid(this.el.find(".grid"), [], {
            column: this._getCols(),
            autoWidth: true,
            autoHeight: true,
            rowInvertSelect:!this.profile.clickToggle,
            headerRow: this.profile.headerRow,
            htmlLayer: 'div',
            rowDragDropGroup: 'GRID1'
        }, cb);
        if(this.profile.headerRow){
            this.el.find(".grid .rtq-grid-hd").css({"display":"block"});
        }
    },
    _createSettingPanel: function(){
        var  self = this,qslang=QS_Lang.marketindices;
        var settingPN = this.profile.isAPI?this.profile.settingPanel||$("body"):this.__winObj.settingPanelObj.settingPN;
        settingPN.addClass('rtq-window-setpn-mki');
        var settingPNGroupBox = new Util.GroupBox(settingPN.find(".wrap")||settingPN, [{
            name: qslang["mk_gdisplay"],
            id: 1
        }], {
            width: 177,
            groupBoxHeight: 150
        });     
        settingPNGroupBox.getGroup(1).bd.html('<h5>'+qslang["mk_gchartscope"]+'</h5>');
        
        new Util.DropDownList(settingPNGroupBox.getGroup(1).bd, function(t, v){
                self.profile.chartRange = v;
                self.changeChartRange(v);
            }, this.getChartRangeData(),
            {width: 163, className:"rtq-ddl-black"}
         );
    },
    getMenuData:function(){
        var menu=[],menulist=this.profile.menuList;
        for(var i=0,l=menulist.length;i<l;i++){
            if(this.regionInfo[menulist[i]]){
                menu.push({id:menulist[i],txt:this.regionInfo[menulist[i]].txt,closable:false});
            }
        }
        return menu;
    },
    getChartRangeData:function(){
        var qslang=QS_Lang.marketindices;
        return [{txt: '1 '+qslang["mk_gchart_day"],val: '1d' }, 
                {txt: '5 '+qslang["mk_gchart_days"],val: '5d' },
                {txt: '1 '+qslang["mk_gchart_month"],val: '1m'}, 
                {txt: '3 '+qslang["mk_gchart_months"],val: '3m'}, 
                {txt: '6 '+qslang["mk_gchart_months"],val: '6m'}, 
                {txt: '1 '+qslang["mk_gchart_year"],val: '1y'}, 
                {txt: '2 '+qslang["mk_gchart_years"],val: '2y'}];
    },
    _activeRow:function(row,bool){
        var symbolEl=row.cells["Symbol"].el;
        var symbolContentEl=symbolEl.find('.rtq-grid-cell-ctn');
        var lastPriceEl=row.cells["LastPrice"].el;   
        if(!bool){
            symbolEl.css({"font-weight":"normal"});
            lastPriceEl.css({"font-weight":"normal"});
        }else{
            symbolEl.css({"font-weight":"bold"});
            lastPriceEl.css({"font-weight":"bold"});
        }
        this.rowHeight=symbolContentEl.height();
    },
    _animateComplete:function(){
        if(this.profile.isAPI){
            this.changeOutSize(this.profile.width||this.el.width(),this.profile.height||this.el.height());
        }else{
            this.changeOutSize();
        }
    },
    _pp0:function (n){
        if (n < 10) 
            n = '0' + n;
        return n;
    },
    _getLastTimefromData:function(d){
        var l = d.length-1,tick=0,time="";
        for(var i=l;i>=0;i--){
            if(!isNaN(d[i][1])){
                tick = d[i][d[i].length-1];
                break;
            }
        }
        if(tick>0){
            var dt = new Date(tick);
            time = this._pp0(dt.getHours())+":"+this._pp0(dt.getMinutes());
        }
        return time;
    },
    _expanseRow:function(row,bool,completeFunction){
        if(!this.profile.chartFixed){
            var self=this;
            row.animate({height: (bool?(self.profile.chartHeight+self.rowHeight+this.staticValue.padheight):self.rowHeight+this.staticValue.padheight)+'px'}, {
                duration: "normal",
                complete: function(){
                    if(completeFunction){completeFunction();}
                }
            });
        }
    },
    _subscribeTicker: function(gkey,endDrawCB,startDrawCB){
        var self = this;
        var pid = gData[gkey]["secId"] || gData[gkey]["performanceId"];
        if(typeof this.showLoading =='function'){
            this.showLoading();
        }
        this.tValidation.checkTickers(pid, function(o){
            self.lastSubscribeTicker = o[0];
            self.miniChart.subscribe(o[0], self.id,self.profile.chartCfg,function(data){
                if(typeof self.hideLoading=='function'){
                    self.hideLoading();
                }
                if (typeof endDrawCB == 'function') {
                    endDrawCB(data);
                }
            },startDrawCB);
        });
    },
    _drawMiniChart:function(row, gkey,endDrawCB,startDrawCB){
        if(!this.profile.chartFixed)
            row.el.append(this.el.find(".minichart").css({"visibility":"hidden"}));  // hide the old chart
        if(!this.miniChart){
            this._initMiniChart(gkey,endDrawCB,startDrawCB);
        }else{
            this.miniChart.unSubscribe(this.lastSubscribeTicker,this.id);
            this._subscribeTicker(gkey,endDrawCB,startDrawCB);
        }
    },
    _initMiniChart: function(gkey, endDrawCB,startDrawCB){
        this.miniChart = new minichart(this.el.find(".minichart"), $.extend(this.profile.chartProfile , {
            width: this.profile.width,
            height: this.profile.chartHeight
        }));
        this._subscribeTicker(gkey, endDrawCB,startDrawCB);
    },
    _reBuildGridData: function(id){
        var self = this;
        if(!this.gKeyList){this.gKeyList={};}
        if(!this.gKeyList[id]){this.gKeyList[id]={};}
        if (!this.gKeyList[id]["gKeyList"]||this.gKeyList[id]["gKeyList"].length == 0) {
            var ls = this.regionInfo[id].tickers;
            if(typeof this.showLoading =='function'){
                this.showLoading();
            }            
            this.tValidation.checkTickers(ls, function(gKeyList){
                if(typeof self.hideLoading=='function'){
                    self.hideLoading();
                }
                self.gKeyList[id]["gKeyList"] = gKeyList;
                var gKeyMap = {};
                for (var i = 0; i < gKeyList.length; i++) {
                    gKeyMap[gKeyList[i]] = i;
                }
                self.gKeyList[id]["gKeyMap"] = gKeyMap;
                
                var data = self._fillDList(gKeyList)
                self.dataGrid.reBindData(data);
                for (var i = 0; i < gKeyList.length; i++) {
                    self._forceUpdateData(gKeyList[i]);
                }
                if (data.length > 0) {
                    self.dataGrid.selectRow(data[0]["id"]);
                }
            });
        }
        else {
            var gKeyList = this.gKeyList[id]["gKeyList"], data = this._fillDList(gKeyList);
            this.dataGrid.reBindData(data);
            for (var i = 0; i < gKeyList.length; i++) {
                this._forceUpdateData(gKeyList[i]);
            }
            if(data.length>0){
                this.dataGrid.selectRow(data[0]["id"]);
            }
        }
        setTimeout(function(){
            self.dataGrid.el.find('.rtq-grid-row:last-child').addClass('last-row');
        },500);//added by wind @ 20120326, for quest public site
    },
    _fillDList: function(gKeyList){
        var data = [];
        for (var i = 0; i < gKeyList.length; i++) {
            var d = {};
            d["id"] = gKeyList[i];
            d["Symbol"] = this.tickersInfo[this.currentTabMenuId][gData[gKeyList[i]]["performanceId"]] ;
            data.push(d);
        }
        return data;
    },
    _forceUpdateData: function(gKey){
        var aData = {};
        var cols = this.dataGrid.getColumnCfg(), field;
        for (var c in cols) {
            field = cols[c].dataIndex;
            if(field=="id") continue;
            if (field == "Up/Down") 
                field = "Chg";
            aData[field] = {
                dataType: cols[c].dataType,
                value: gData[gKey] == null ? null : push.proxy.getMarketQuoteData(gKey, field).value
            };
        }
        this.updateData(gKey, aData, false);
    },
    fileMenuCallback: function(v){//for terminal
        if (v == "refresh") {
            
        }
    },
    clear:function(){
        for (var p in this) {
            if (!p || p == 'clear') {
                continue;
            }
            this[p] = null;
            delete this[p];
        }
    },

    changeOutSize: function(w,h){
        //alert("change size"+w+":"+h);
        if(this.profile.isAPI){
            w = this.profile.width||w||this.container.width();
            h = this.profile.height||h||this.container.height();
        }else{
            //if it is terminal, the height of win-bd is static
            w = w||this.container.parent().width();
            h = h||this.container.parent().height();
            this.el.css({
                width: "auto"
            });
            if(this.profile.width>=300){
                this.el.find(".tabmenu").removeClass("homepage");
            }
        }
        if (w < this.staticValue.minWidth) {
            w = this.staticValue.minWidth;
        }
        this.dataGrid.resize(w,null);
        if(this.activeRow&&!this.profile.chartFixed){
            var symbolEl=this.activeRow.cells["Symbol"].el.find('.rtq-grid-cell-ctn');
            this.rowHeight=symbolEl.height();
            this.activeRow.el.css({height:this.profile.chartHeight+this.rowHeight+this.staticValue.padheight});
        }
        var self=this;
        if (this.profile.fixHeight) {
            var tabHeight=this.el.find(".tabmenu .rtq-tab-wrap").height(),titleHeight=this.el.find(".title").height()||0;
            Util.DelayRun('changeOutSize.marketindex', function(){
                self.scrollPanel.reSize(w, h-tabHeight);
                if (self.scrollPanel.scrollbarY.isShow) {
                    w = w - 13;
                }
                self._changeMinChartSize(w, self.profile.chartHeight);
            }, 200, self);
        }
        else {
            this.scrollPanel.reSize(w,null);
            h = this.el.height();
        }
        this._onHeightChange(h);
    },
    _changeMinChartSize:function(w,h){  // cal miniChart Size.
        if(!this.activeRow) return;
        this.el.find(".miniChart").css({width:w,height:h});
        if (this.miniChart) {
            this.miniChart.changeOutSize(w, h);
        }
    },
    updateData: function(gKey, aData, needFlash){
        if (this.gKeyList[this.currentTabMenuId]["gKeyMap"]&&this.gKeyList[this.currentTabMenuId]["gKeyMap"].hasOwnProperty(gKey)) {
            var _flashMethod = needFlash === false ? (function(){}) : flash,decimal=2,ellipsis=false,nubtag=false;
            if(this.profile.tabConfig[this.currentTabMenuId]&&typeof this.profile.tabConfig[this.currentTabMenuId].decimal!="undefined"){
                decimal=this.profile.tabConfig[this.currentTabMenuId].decimal;
            }
            for (var field in aData) {
                var type = aData[field].dataType,gValue = aData[field].value,oldData = aData[field].oValue;
                var data = gValue,el = this.dataGrid.DOMMap[gKey][field],colConfig=this.columnMap[field];
                nubtag=false,ellipsis=false;
                if(!el||el == null) continue;
                var securitytype = gData[gKey]["type"];
                switch (field) {
                    case 'LastPrice':
                        typeof(el) == "undefined" ? null:_flashMethod(el, data, oldData);
                        break;
                    case "Date":
                       data =  gData[gKey]["TradeDate"]||'';
                       break;
                    case 'Chg':
                    case 'Chg%':
                        if (needFlash !== false && typeof(el) != "undefined") {
                            flashWithDirectional(el, data, oldData, data >= 0);
                        }else if(typeof(el) != "undefined"){
                            el.style.color = (data >= 0 ? QS_Style.greenFontColor : QS_Style.redFontColor);
                        }
                        if (field == "Chg") { // update the up/down column;
                            var upd = data;
                            if (upd == 0 || typeof upd == 'undefined') {
                                upd = '';
                            }else {
                                var cls = upd > 0 ? "up" : "down";
                                upd = '<a class="updown ' + cls + '" href="javascript:void(0)">' + cls + '</a>';
                            }
                            var upEl = this.dataGrid.DOMMap[gKey]["UpDown"];
                            if (upEl) 
                                upEl.innerHTML = upd;
                        }
                        break;
                    default:
                        break;
                }
                nubtag=(colConfig&&colConfig["dataType"]=="float")?true:false
                if(nubtag){
                    if(!isNaN(data)){
                        if(colConfig&&typeof colConfig.decimal!='undefined'){
                            decimal =colConfig.decimal;
                        }
                        if(field == 'Chg%'&&/^[-\+]?\d+(\.\d+)?$/.exec(data) && this.profile.percentage){
                            data = formatDoubledata(data,securitytype,decimal,this.profile.isFormat,this.profile.isUnit,this.profile.numberSeparate) + "%";
                        }else{
                            data = formatDoubledata(data,securitytype,decimal,this.profile.isFormat,this.profile.isUnit,this.profile.numberSeparate);
                        }
                    }else{
                         data=this.staticValue.defaultValue;
                    }
                }
                if (field == 'Symbol')  continue;
                ellipsis = colConfig?colConfig["ellipsis"]:false;
                if (!ellipsis) {
                    if(colConfig&&colConfig["renderer"]){
                        $(el).html(colConfig["renderer"](data));
                    }else{
                        el[this._textKey] = data;
                    }
                }else{
                    el[this._textKey] = data;
                }               
            }
        }
    },
    _onHeightChange:function(height){
        if (!this.loaded) {
            this.lastCallbackHeight = height;
            if (typeof this.callback.onLoad == 'function') {
                this.loaded = true;
                this.callback.onLoad({
                    component: 'marketIndex',
                    height: height,
                    minWidth:this.staticValue.minWidth
                });
            }
        }else {
            if (this.lastCallbackHeight != height) {
                this.lastCallbackHeight = height;
                if (typeof this.callback.onHeightChange == 'function') {
                    this.callback.onHeightChange({
                        height: this.lastCallbackHeight,
                        component: 'marketIndex'
                    });
                }
            }
        }
    },
    changeChartRange:function(r){
        var self=this;
        var l = r.length - 1, step = parseInt(r.substr(0,l));
        var today = new Date(), todayIdx = RTQ_ChartUtil.toDateIndex(today);
        var cfg = {"endIndex":todayIdx}; 
        switch (r.charAt(l)) {
            case "d":
                cfg["freq"] = 1;
                cfg["startIndex"] = todayIdx - (step - 1);
                cfg["days"] = step;
                break;
            case "m":
                var y = today.getFullYear(), m = today.getMonth();
                if (m > step - 1) {
                    m = m - step;
                }
                else {
                    y -= 1;
                    m = m + 12 - step;
                }
                var startDate = new Date(y, m, today.getDate());
                cfg["startIndex"] = RTQ_ChartUtil.toDateIndex(startDate);
                
                if (todayIdx - cfg["startIndex"] >= 60) {
                    cfg["freq"] = "d";
                }else{
                    cfg["freq"] = 30;
                }
                break;
            case "y":
                cfg["freq"] = "d";
                var y = today.getFullYear() - step, m = today.getMonth(),d = today.getDate();
                var startDate = new Date(y, m, d);
                cfg["startIndex"] = RTQ_ChartUtil.toDateIndex(startDate);
                break;
            default:
                break;
        }
        
        
        this.profile.chartCfg = cfg||{};
        if(this.miniChart&&this.activeRow){
            var gkey = this.activeRow.id;
            this._drawMiniChart(this.activeRow, gkey,function(data){
                self.el.find(".minichart").css("visibility","visible");
                if(self.profile.showTime){
                    var time = self._getLastTimefromData(data);
                    self.el.find('.rtc-legend-txt .time').html(time);
                }
            },function(data){
                self.onStartDraw(data);
            });
        }
    }
};
